package com.gzc.just.play.last.war.centralserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.centralserver.service.MatchmakingService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 匹配处理器
 * 处理玩家匹配相关的消息，如开始匹配、取消匹配等
 */
@Component("central-matchmakingHandler")
public class MatchmakingHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(MatchmakingHandler.class);
    
    @Autowired
    private MatchmakingService matchmakingService;
    
    private static final int MATCHMAKING = 3003;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        
        // 从消息中解析操作类型
        String operation = extractOperation(message);
        
        switch (operation) {
            case "startMatchmaking":
                handleStartMatchmaking(playerId, message, ctx);
                break;
            case "cancelMatchmaking":
                handleCancelMatchmaking(playerId, ctx);
                break;
            case "getMatchmakingStatus":
                handleGetMatchmakingStatus(playerId, ctx);
                break;
            default:
                logger.warn("Unknown matchmaking operation: {}", operation);
                break;
        }
    }
    
    /**
     * 处理开始匹配请求
     */
    private void handleStartMatchmaking(Long playerId, Object message, ChannelHandlerContext ctx) {
        // 从消息中解析匹配参数
        Map<String, Object> matchParams = extractMatchParams(message);
        
        // 开始匹配
        String matchId = matchmakingService != null ? matchmakingService.startMatchmaking(playerId, matchParams) : null;
        
        // 发送开始匹配响应
        if (matchId != null) {
            sendStartMatchmakingResponse(ctx, matchId, true, "Matchmaking started successfully");
            logger.info("Started matchmaking for player: {}", playerId);
        } else {
            sendStartMatchmakingResponse(ctx, null, false, "Failed to start matchmaking");
            logger.error("Failed to start matchmaking for player: {}", playerId);
        }
    }
    
    /**
     * 处理取消匹配请求
     */
    private void handleCancelMatchmaking(Long playerId, ChannelHandlerContext ctx) {
        // 取消匹配
        boolean success = matchmakingService != null ? matchmakingService.cancelMatchmaking(playerId) : false;
        
        // 发送取消匹配响应
        if (success) {
            sendCancelMatchmakingResponse(ctx, true, "Matchmaking cancelled successfully");
            logger.info("Cancelled matchmaking for player: {}", playerId);
        } else {
            sendCancelMatchmakingResponse(ctx, false, "Not in matchmaking queue");
            logger.warn("Player {} tried to cancel but not in queue", playerId);
        }
    }
    
    /**
     * 处理获取匹配状态请求
     */
    private void handleGetMatchmakingStatus(Long playerId, ChannelHandlerContext ctx) {
        // 获取匹配状态
        MatchmakingService.MatchmakingStatus status = matchmakingService != null ? 
            matchmakingService.getMatchmakingStatus(playerId) : new MatchmakingService.MatchmakingStatus(false, 0, 0);
        
        // 转换为Map以便序列化
        Map<String, Object> statusMap = new HashMap<>();
        statusMap.put("isInQueue", status.isInQueue());
        statusMap.put("queueSize", status.getQueueSize());
        statusMap.put("waitTime", status.getWaitTime());
        
        // 发送匹配状态响应
        sendMatchmakingStatusResponse(ctx, statusMap, true, "Matchmaking status retrieved successfully");
        logger.info("Retrieved matchmaking status for player: {} (inQueue: {}, queueSize: {})", 
                   playerId, status.isInQueue(), status.getQueueSize());
    }
    
    // 以下是辅助方法，用于从消息中提取数据
    
    private String extractOperation(Object message) {
        // 实际实现中应从消息对象中解析操作类型
        return "startMatchmaking"; // 简化实现
    }
    
    private Map<String, Object> extractMatchParams(Object message) {
        // 实际实现中应从消息对象中解析匹配参数
        Map<String, Object> params = new HashMap<>();
        params.put("playerName", "TestPlayer"); // 简化实现
        params.put("level", 1);
        return params;
    }
    
    // 以下是发送响应的方法
    
    private void sendStartMatchmakingResponse(ChannelHandlerContext ctx, String matchId, 
                                         boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending start matchmaking response: success={}, matchId={}", success, matchId);
    }
    
    private void sendCancelMatchmakingResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending cancel matchmaking response: success={}", success);
    }
    
    private void sendMatchmakingStatusResponse(ChannelHandlerContext ctx, Map<String, Object> status,
                                           boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending matchmaking status response: success={}", success);
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
    
    @Override
    public int getMessageId() {
        return MATCHMAKING;
    }
    
    @Override
    public String getName() {
        return "MatchmakingHandler";
    }
}